package cn.dao.impl;

import cn.dao.UserDao;
import cn.domain.User;
import cn.util.JDBCutils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class UserDaoimpl implements UserDao {
    private  JdbcTemplate template=new JdbcTemplate(JDBCutils.getDataSource());
    public List<User> findAll() {
        //直接去数据库查询JDBC
        String sql="select * from user";
        List<User> users=template.query(sql,new BeanPropertyRowMapper<User>(User.class));
        return users;
    }

    @Override
    public User FindUserByUsernameAndPassword(String username,String password) {
        try {
            String sql="select * from user where username=? and password=?";
            User user1 = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), username, password);
            return user1;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void addUser(User user) {
        String sql="insert into user values(null,?,?,?,?,?,?,null,null)";
        template.update(sql,user.getName(),user.getAge(),user.getGender(),user.getAddress(),user.getQq(),user.getEmail());

    }

    @Override
    public void deleteUser(int id) {
        String sql="delete  from user where id=?";
        template.update(sql,id);
    }

    @Override
    public User findUserByid(int id) {
        try {
            String sql="select * from user where id=?";
            User user1 = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), id);
            return user1;
        } catch (DataAccessException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void updateUser(User user) {
        String sql="update user set name =? ,gender =? ,age =? ,address=? ,qq=? ,email=? where id=?";
        template.update(sql,user.getName(),user.getGender(),user.getAge(),user.getAddress(),user.getQq(),user.getEmail(),user.getId());

    }
}
